/*
 * iShopPlace Project.
 */
package ishopplace.view.bean;

import ishopplace.model.exception.iShopPlaceException;
import ishopplace.view.util.FacesUtils;

import java.util.List;
import java.util.ArrayList;
import java.util.StringTokenizer;

import org.springframework.beans.support.PagedListHolder;


/**
 * Search page backing bean for the search page.
 * 
 * @author <a href="mailto:derek@derekshen.com">Derek Y. Shen</a>
 */
public class SearchPageBean extends BasePaginationBean {
    private String keywords;
    
    public SearchPageBean() {
    	super();
    	this.logger.debug("SearchPageBean is created");
    }
    
    /**
     * Backing bean action to search products.
     * 
     * @return the navigation result
     */
    public String searchAction() {
        this.logger.debug("searchAction is invoked");
        this.logger.debug("keywords = " + keywords);
        
        try {
            this.setPagedListHolder(new PagedListHolder(
            	this.serviceLocator.getCatalogService().searchProductList(this.parseKeywords())));
    		//put in the session
    		FacesUtils.getSessionBean().setCurrentSearchKeywords(this.keywords);
    		FacesUtils.getSessionBean().setCurrentSearchResult(this.pagedListHolder);
            return NavigationResults.SEARCH_RESULT;
        } catch (iShopPlaceException me) {
            String msg = "Could not search by keywords";
            this.logger.error(msg, me);
            FacesUtils.addErrorMessage(msg + ": Internal Error");
            return NavigationResults.FAILURE;
        }
    }
    
    /**
     * Backing bean action to navigate to another page.
     * 
     * @return the navigation result
     */
    public String navigateAction() {
    	this.keywords = FacesUtils.getSessionBean().getCurrentSearchKeywords();
    	this.pagedListHolder = FacesUtils.getSessionBean().getCurrentSearchResult();
    	
    	if (this.pagedListHolder == null) {
    		String msg = "Could not find result in session";
    		this.logger.error(msg);
    		FacesUtils.addErrorMessage(msg, ": Internal Error");
    		return NavigationResults.FAILURE;
    	}
    	this.nagivate();
		return NavigationResults.SEARCH_RESULT;
    }
    
    public String getKeywords() {
        return this.keywords;
    }
    
    public void setKeywords(String newKeyword) {
        this.keywords = newKeyword;
    }
    
    private List parseKeywords() {
    	StringTokenizer st = new StringTokenizer(this.keywords);
    	List list = new ArrayList();
    	while (st.hasMoreTokens()) {
    		list.add(st.nextToken());
    	}
    	return list;
    }
}
